<!--------------------------------
 - @Author: Your Name
 - @LastEditor: Your Name
 - @LastEditTime: 2025-11-09
 - Copyright © 2025 Your Name
 --------------------------------->

<template>
  <CommonPage>
    <template #action>
      <NButton v-permission="'AddDesignFileTag'" type="primary" @click="handleCreate()">
        <i class="i-material-symbols:add mr-4 text-18" />
        新增标签
      </NButton>
    </template>

    <MeCrud
      ref="$table"
      v-model:query-items="queryItems"
      :columns="columns"
      :get-data="api.read"
    >
      <MeQueryItem label="标签名称" :label-width="80">
        <n-input
          v-model:value="queryItems.name"
          type="text"
          placeholder="请输入标签名称"
          clearable
        />
      </MeQueryItem>
    </MeCrud>

    <!-- 创建/编辑标签模态框 -->
    <MeModal ref="formModalRef" width="500px" :title="modalTitle">
      <n-form
        ref="formRef"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="formData"
        :rules="formRules"
      >
        <n-form-item label="标签名称" path="name">
          <n-input
            v-model:value="formData.name"
            placeholder="请输入标签名称"
          />
        </n-form-item>

        <n-form-item label="标签颜色" path="color">
          <NColorPicker
            v-model:value="formData.color"
            :show-alpha="false"
            :modes="['hex']"
          />
          <n-input
            v-model:value="formData.color"
            placeholder="或输入颜色值"
            :style="{ width: '120px', marginLeft: '8px' }"
          />
        </n-form-item>
      </n-form>

      <template #footer>
        <n-space justify="end">
          <NButton @click="formModalRef?.close()">
            取消
          </NButton>
          <NButton type="primary" :loading="submitLoading" @click="handleSubmit">
            提交
          </NButton>
        </n-space>
      </template>
    </MeModal>
  </CommonPage>
</template>

<script setup>
import { NButton, NColorPicker, NTag } from 'naive-ui'
import { MeCrud, MeModal, MeQueryItem } from '@/components'
import { formatDateTime } from '@/utils'
import tagApi from './api'

defineOptions({ name: 'DesignFileTagMgt' })

// 将tagApi重命名为api，以匹配MeCrud使用的属性名
const api = tagApi

const $table = ref(null)
/** QueryBar筛选参数（可选） */
const queryItems = ref({})

onMounted(() => {
  $table.value?.handleSearch()
})

// 模态框相关
const formModalRef = ref(null)
const formRef = ref(null)
const modalTitle = ref('')
const formData = ref({
  id: null,
  name: '',
  color: '#18a058',
})
const submitLoading = ref(false)

// 表单验证规则
const formRules = {
  name: {
    required: true,
    message: '请输入标签名称',
    trigger: ['input', 'blur'],
  },
  color: {
    required: true,
    message: '请选择标签颜色',
    trigger: ['change'],
  },
}

// 操作列
const columns = [
  { title: 'ID', key: 'id', width: 100 },
  {
    title: '标签名称',
    key: 'name',
    width: 200,
    render: (row) => {
      return h(NTag, {
        type: 'success',
        color: { color: row.color, textColor: '#fff' },
      }, { default: () => row.name })
    }
  },
  {
    title: '标签颜色',
    key: 'color',
    width: 150,
    render: (row) => {
      return [
        h('div', {
          style: {
            display: 'inline-block',
            width: '20px',
            height: '20px',
            backgroundColor: row.color,
            border: '1px solid #ddd',
            borderRadius: '4px',
            marginRight: '8px'
          }
        }),
        h('span', row.color)
      ]
    }
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180,
    render(row) {
      return h('span', formatDateTime(row.createTime))
    },
  },
  {
    title: '更新时间',
    key: 'updateTime',
    width: 180,
    render(row) {
      return h('span', formatDateTime(row.updateTime))
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    align: 'center',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            class: 'ml-12px',
            onClick: () => handleEdit(row),
          },
          { default: () => '编辑' },
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            style: 'margin-left: 12px;',
            onClick: () => handleDelete(row.id),
          },
          { default: () => '删除' },
        ),
      ]
    },
  },
]

// 打开创建模态框
function handleCreate() {
  formData.value = {
    id: null,
    name: '',
    color: '#18a058',
  }
  modalTitle.value = '创建标签'
  formModalRef.value?.open()
}

// 打开编辑模态框
function handleEdit(row) {
  formData.value = { ...row }
  modalTitle.value = '编辑标签'
  formModalRef.value?.open()
}

// 提交表单
async function handleSubmit() {
  try {
    await new Promise((resolve, reject) => {
      formRef.value?.validate((errors) => {
        if (errors) {
          console.log('表单验证失败:', errors)
          reject(new Error('表单验证失败'))
        } else {
          console.log('表单验证通过')
          resolve()
        }
      })
    })

    submitLoading.value = true

    if (formData.value.id) {
      // 更新
      await tagApi.update(formData.value)
      $message.success('标签更新成功')
    } else {
      // 创建
      await tagApi.create(formData.value)
      $message.success('标签创建成功')
    }

    submitLoading.value = false
    formModalRef.value?.close()
    $table.value?.handleSearch()
  } catch (error) {
    submitLoading.value = false
    $message.error(error.message || '操作失败')
    console.error('操作失败:', error)
  }
}

// 删除标签
function handleDelete(id) {
  const d = $dialog.warning({
    content: '确定删除该标签？',
    title: '提示',
    positiveText: '确定',
    negativeText: '取消',
    async onPositiveClick() {
      try {
        d.loading = true
        await tagApi.delete(id)
        $message.success('删除成功')
        d.loading = false
        $table.value?.handleSearch()
      } catch (error) {
        console.error(error)
        d.loading = false
        $message.error(error.message || '删除失败')
      }
    },
  })
}
</script>